package br.com.firula.bo.impl;

import java.util.Date;
import java.util.List;

import br.com.firula.bo.GenericBO;
import br.com.firula.dao.GenericDAO;
import br.com.firula.to.BaseTO;
import br.com.firula.web.filter.Filtro;

public class GenericBOImpl implements GenericBO {
	protected GenericDAO dao;
	private Class<BaseTO> clazz;

    public void setType(String type) {
        try {
        	this.clazz = (Class<BaseTO>) Class.forName(type);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
    }
  	/*public void setFiltraAtivos(boolean filtraAtivos) {
		dao.setFiltraAtivos(filtraAtivos);
	}*/
    public Class getClazz(){
    	return clazz;
    }
    
	public List getList(Filtro filtro) {
		return dao.findByFilter(filtro);	
	}

	public List<BaseTO> getListByExamples(BaseTO[] examples, int first, int max) {
		return dao.findByExample(examples, first, max);
	}
	
	public List<BaseTO> getListByExample(BaseTO example, int first, int max){
		return dao.findByExample(example, first, max);
	}
	
    public BaseTO get(String id) {
    	BaseTO to = dao.findById(clazz, Long.valueOf(id));
    	return to;
    }

    public void save(BaseTO object) {
    	if(object.getId() == null)
    		object.setDataCriacao(new Date());
    	else object.setDataAlteracao(new Date());
    	dao.saveOrUpdate(object);
    }

    public void remove(String id) {
    	BaseTO to = get(id);
    	to.setRemovido(Boolean.TRUE);
    	to.setDataRemocao(new Date());
    	dao.saveOrUpdate(to);
    	//dao.remove(to);
    }   

    public Integer getListCount(Filtro filter){
    	int count = dao.countByFilter(filter);
		return count;
    }
    
    public Integer getListCountByExamples(BaseTO[] examples){
    	int count = dao.countByExample(examples);
    	return count;
    }
    
    public List<BaseTO> getListByExample(BaseTO example,String search, String qtde, String page){
    	int pag = page == null ? 1 : Integer.parseInt(page);
    	int qtd = qtde == null ? 50 : Integer.parseInt(qtde);
    	return dao.findByExample(example, (pag - 1) * qtd + 0, qtd);
    }
}
